package com.spsoft.vatoutinv.service.matchflow.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.exception.BusinessException;
import com.spsoft.core.model.Result;
import com.spsoft.core.model.bo.TokenUser;
import com.spsoft.core.utils.BeanUtils;
import com.spsoft.core.utils.ExcelUtils;
import com.spsoft.core.utils.SecurityUtils;
import com.spsoft.system.entity.NvatOutInvoiceDetails;
import com.spsoft.system.entity.NvatOutInvoiceItems;
import com.spsoft.system.entity.NvatRevmapinvoitems;
import com.spsoft.system.entity.NvatTrandtadvaltaxsep;
import com.spsoft.system.mapper.NvatOutInvoiceItemsMapper;
import com.spsoft.system.mapper.NvatRevmapinvoitemsMapper;
import com.spsoft.system.service.NvatRevmapinvoitemsService;
import com.spsoft.vatoutinv.constants.CommonConstant;
import com.spsoft.vatoutinv.constants.DictConstant;
import com.spsoft.vatoutinv.entity.matchflow.VmsMatching;
import com.spsoft.vatoutinv.entity.matchflow.VmsMatchingDetail;
import com.spsoft.vatoutinv.entity.vmsfulloutinvoice.VmsFullOutInvoiceDetails;
import com.spsoft.vatoutinv.enums.CommonEnum;
import com.spsoft.vatoutinv.mapper.VatNvatOutInvoiceDetailsMapper;
import com.spsoft.vatoutinv.mapper.VmsNvatTrandtadvaltaxsepMapper;
import com.spsoft.vatoutinv.model.dto.matchflow.VmsMatchFlowPageDto;
import com.spsoft.vatoutinv.model.vo.matchflow.VmsMatchFlowApplyVo;
import com.spsoft.vatoutinv.model.vo.matchflow.VmsMatchInvoiceDetailVo;
import com.spsoft.vatoutinv.model.vo.matchflow.VmsMatchInvoiceInfoVo;
import com.spsoft.vatoutinv.model.vo.matchflow.VmsMatchInvoiceItemVo;
import com.spsoft.vatoutinv.model.vo.matchflow.excel.VmsMatchFlowRevokeExcelVo;
import com.spsoft.vatoutinv.model.vo.vmstransactionflowinvoice.VmsTransacitonFlowInvoiceItemVo;
import com.spsoft.vatoutinv.service.matchflow.VmsMatchFlowRevokeService;
import com.spsoft.vatoutinv.service.matchflow.VmsMatchingDetailService;
import com.spsoft.vatoutinv.service.matchflow.VmsMatchingService;
import com.spsoft.vatoutinv.service.translate.impl.DictTranslate;
import com.spsoft.vatoutinv.service.vmsfulloutinvoice.VmsFullOutInvoiceDetailsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 手工匹配流水撤销 服务实现类
 *
 * @author : chenxudong
 * @date : 2024/6/25 11:09
 */
@Slf4j
@Service
@RequiredArgsConstructor
@SuppressWarnings({"unchecked"})
public class VmsMatchFlowRevokeServiceImpl implements VmsMatchFlowRevokeService {

    public static final String LOG_MSG = "(手工匹配流水撤销实现层)";

    private final DictTranslate dictTranslate;

    private final VmsMatchingService vmsMatchingService;

    private final VmsMatchingDetailService vmsMatchingDetailService;

    private final VatNvatOutInvoiceDetailsMapper nvatOutInvoiceDetailsMapper;

    private final NvatOutInvoiceItemsMapper nvatOutInvoiceItemsMapper;

    private final VmsNvatTrandtadvaltaxsepMapper vmsNvatTrandtadvaltaxsepMapper;

    private final NvatRevmapinvoitemsMapper nvatRevmapinvoitemsMapper;

    private final VmsFullOutInvoiceDetailsService vmsFullOutInvoiceDetailsService;

    private final NvatRevmapinvoitemsService nvatRevmapinvoitemsService;

    @Override
    public Result<IPage<VmsMatchFlowApplyVo>> pageApply(VmsMatchFlowPageDto pageDto) {
        // 创建分页对象
        Page<VmsMatchFlowApplyVo> page = new Page<>(pageDto.getPageNo(), pageDto.getPageSize());
        // 交易机构下拉框处理
        String deptCode = pageDto.getDeptCode();
        if (StringUtils.isNotBlank(deptCode)) {
            List<String> deptCodeList = Arrays.asList(deptCode.split(","));
            pageDto.setDeptCodeList(deptCodeList);
        } else {
            pageDto.setDeptCodeList(Collections.singletonList(SecurityUtils.getDeptCode()));
        }
        // 匹配撤销日期处理 将yyyy-MM-dd转为yyyy-mm-dd hh24:mi:ss
        if (StringUtils.isNotBlank(pageDto.getPprqq()) && StringUtils.isNotBlank(pageDto.getPprqz())) {
            pageDto.setPprqq(DateUtil.format(DateUtil.beginOfDay(DateUtil.parseDate(pageDto.getPprqq())), CommonConstant.DATE_FORMAT_14));
            pageDto.setPprqz(DateUtil.format(DateUtil.endOfDay(DateUtil.parseDate(pageDto.getPprqz())), CommonConstant.DATE_FORMAT_14));
        }
        // 获取手工匹配流水撤销记录
        IPage<VmsMatchFlowApplyVo> matchFlowList = vmsMatchingService.pageApply(page, pageDto);
        return Result.OK(matchFlowList);
    }

    @Override
    public void export(VmsMatchFlowPageDto pageDto, HttpServletResponse response) {
        try {
            // 交易机构下拉框处理
            String deptCode = pageDto.getDeptCode();
            if (StringUtils.isNotBlank(deptCode)) {
                List<String> deptCodeList = Arrays.asList(deptCode.split(","));
                pageDto.setDeptCodeList(deptCodeList);
            } else {
                pageDto.setDeptCodeList(Collections.singletonList(SecurityUtils.getDeptCode()));
            }
            // 匹配日期处理 将yyyy-MM-dd转为yyyy-mm-dd hh24:mi:ss
            if (StringUtils.isNotBlank(pageDto.getPprqq()) && StringUtils.isNotBlank(pageDto.getPprqz())) {
                pageDto.setPprqq(DateUtil.format(DateUtil.beginOfDay(DateUtil.parseDate(pageDto.getPprqq())), CommonConstant.DATE_FORMAT_14));
                pageDto.setPprqz(DateUtil.format(DateUtil.endOfDay(DateUtil.parseDate(pageDto.getPprqz())), CommonConstant.DATE_FORMAT_14));
            }
            // 获取手工匹配流水撤销记录，不分页
            List<VmsMatchFlowApplyVo> matchFlowList = vmsMatchingService.getApplyData(pageDto);
            if (CollectionUtil.isEmpty(matchFlowList)) {
                throw new BusinessException(ResponseEnum.DATA_NOT_FIND_ERROR);
            }
            // 数据转换
            List<VmsMatchFlowRevokeExcelVo> excelVoList = BeanUtils.copyListProperties(matchFlowList, VmsMatchFlowRevokeExcelVo::new, (s, t) -> {
                // 导出时需要将字典值转换
                t.setFplx(dictTranslate.translate(DictConstant.VMS_FPLX, s.getFplx()));
                t.setKprq(DateUtil.format(s.getKprq(), CommonConstant.DATE_FORMAT_8));
            });
            // 添加序号
            for (int i = 0; i < excelVoList.size(); i++) {
                excelVoList.get(i).setXh(i + 1);
            }

            // excel导出到指定模板中
            String rootPath = "export/matchFlowRevokeTemplate.xlsx";
            InputStream fis = Thread.currentThread().getContextClassLoader().getResourceAsStream(rootPath);
            if (fis == null) {
                log.error("{}模板下载异常,读取不到文件", LOG_MSG);
                throw new BusinessException(ResponseEnum.BUSINESS_EXCEL_TEMPLATE_ERROR);
            }
            // 导出
            ExcelUtils.exportExcelWithTemplate(excelVoList, "发票匹配流水撤销记录", response, fis);
        } catch (Exception e) {
            log.error("{}导出excel出现异常", LOG_MSG, e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<VmsMatchInvoiceInfoVo> fastAdd(String fpdm, String fphm, Long applyId, TokenUser tokenUser) {
        if (StringUtils.isBlank(fphm)) {
            return Result.ERROR(ResponseEnum.FPHM_EMPTY_ERROR);
        }
        if (ObjectUtil.isEmpty(applyId)) {
            return Result.ERROR(ResponseEnum.APPLY_ID_EMPTY_ERROR);
        }

        // 查询老系统发票信息
        LambdaQueryWrapper<NvatOutInvoiceDetails> invoiceQuery = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(fpdm)) {
            invoiceQuery.eq(NvatOutInvoiceDetails::getFpdm, fpdm);
        }
        invoiceQuery.eq(NvatOutInvoiceDetails::getFphm, fphm);
        invoiceQuery.eq(NvatOutInvoiceDetails::getQydjid, tokenUser.getDeptCode());
        NvatOutInvoiceDetails nvatOutInvoiceDetail = nvatOutInvoiceDetailsMapper.selectOne(invoiceQuery);
        if (nvatOutInvoiceDetail == null) {
            return Result.ERROR(ResponseEnum.INVOICE_NOT_FOUND);
        }

        // 校验匹配状态
        if (!CommonEnum.MATCHING_STATUS_1.getKey().equals(nvatOutInvoiceDetail.getPpzt())) {
            return Result.ERROR(ResponseEnum.MATCH_FLOW_REVOKE_PPZT_ERROR);
        }

        // 判断发票匹配流水撤销是否存在未结束的流程
        Result<Object> result = vmsMatchingService.judgeProcessIsFinish(CommonEnum.MATCH_FLOW_TYPE_1.getKey(),
                fpdm, fphm, tokenUser.getDeptCode(), applyId, nvatOutInvoiceDetail.getOidid());
        if (!ResponseEnum.SUCCESS.getCode().equals(result.getCode())) {
            return Result.ERRORT(result.getCode(), result.getMessage());
        }

        // 查询发票明细信息
        LambdaQueryWrapper<NvatOutInvoiceItems> itemQuery = new LambdaQueryWrapper<>();
        itemQuery.eq(NvatOutInvoiceItems::getOidid, nvatOutInvoiceDetail.getOidid());
        itemQuery.orderByAsc(NvatOutInvoiceItems::getIviid);
        List<NvatOutInvoiceItems> nvatOutInvoiceItemList = nvatOutInvoiceItemsMapper.selectList(itemQuery);

        // 查询该发票已匹配的流水记录
        LambdaQueryWrapper<NvatRevmapinvoitems> query = new LambdaQueryWrapper<>();
        query.eq(NvatRevmapinvoitems::getOidid, nvatOutInvoiceDetail.getOidid());
        query.orderByAsc(NvatRevmapinvoitems::getIviid, NvatRevmapinvoitems::getRdid);
        List<NvatRevmapinvoitems> nvatRevmapinvoitemList = nvatRevmapinvoitemsService.list(query);
        if (CollectionUtil.isEmpty(nvatRevmapinvoitemList)) {
            return Result.ERROR(ResponseEnum.NOT_FIND_MATCH_FLOW_ERROR);
        }

        // 保存在手工匹配流水表和匹配详细表中
        Long matid = saveMatchData(applyId, tokenUser, nvatRevmapinvoitemList, nvatOutInvoiceDetail, nvatOutInvoiceItemList);

        // 实体类转换
        VmsMatchInvoiceDetailVo invoiceDetailVo = vmsMatchingService.convertToDetailVo(nvatOutInvoiceDetail, matid);
        List<VmsMatchInvoiceItemVo> invoiceItemVoList = BeanUtils.copyListProperties(nvatOutInvoiceItemList, VmsMatchInvoiceItemVo::new);

        // 构建返回数据
        VmsMatchInvoiceInfoVo invoiceInfoVo = new VmsMatchInvoiceInfoVo();
        invoiceInfoVo.setInvoiceDetail(invoiceDetailVo);
        invoiceInfoVo.setInvoiceItemList(invoiceItemVoList);

        return Result.OK(invoiceInfoVo);
    }

    /**
     * 将发票当前的匹配记录保存下来
     * @param applyId 审批流id
     * @param tokenUser 登录用户
     * @param nvatRevmapinvoitemList 发票已匹配的流水记录
     * @param nvatOutInvoiceDetail 发票主信息
     * @param nvatOutInvoiceItemList 发票明细信息
     */
    private Long saveMatchData(Long applyId, TokenUser tokenUser, List<NvatRevmapinvoitems> nvatRevmapinvoitemList,
                               NvatOutInvoiceDetails nvatOutInvoiceDetail, List<NvatOutInvoiceItems> nvatOutInvoiceItemList) {
        // 根据流水id查询流水信息
        List<Long> rdidList = nvatRevmapinvoitemList.stream().map(NvatRevmapinvoitems::getRdid).collect(Collectors.toList());
        List<VmsTransacitonFlowInvoiceItemVo> rdidInfoList = vmsNvatTrandtadvaltaxsepMapper.selectInvoiceByIds(rdidList);

        // 计算流水金额、税额总和
        BigDecimal lsjeTotal = BigDecimal.ZERO, lsseTotal = BigDecimal.ZERO;
        for (VmsTransacitonFlowInvoiceItemVo rdidInfo : rdidInfoList) {
            lsjeTotal = lsjeTotal.add(rdidInfo.getBhsje().add(rdidInfo.getXxse()));
            lsseTotal = lsseTotal.add(rdidInfo.getXxse());
        }

        LambdaQueryWrapper<VmsMatching> query1 = new LambdaQueryWrapper<>();
        query1.eq(VmsMatching::getApplyId, applyId);
        VmsMatching vmsMatching = vmsMatchingService.getOne(query1);
        if (vmsMatching != null) {
            // 删除手工匹配流水撤销信息
            vmsMatchingService.remove(query1);
            // 删除手工匹配流水撤销详细信息
            LambdaQueryWrapper<VmsMatchingDetail> query2 = new LambdaQueryWrapper<>();
            query2.eq(VmsMatchingDetail::getMatid, vmsMatching.getMatid());
            vmsMatchingDetailService.remove(query2);
        }

        // 保存发票匹配流水记录
        VmsMatching vmsMatch = new VmsMatching();
        vmsMatch.setApplyId(applyId);
        vmsMatch.setApplyType(CommonEnum.MATCH_FLOW_TYPE_1.getKey());
        vmsMatch.setFplx(nvatOutInvoiceDetail.getFplxdm());
        vmsMatch.setFpdm(nvatOutInvoiceDetail.getFpdm());
        vmsMatch.setFphm(nvatOutInvoiceDetail.getFphm());
        vmsMatch.setFpje(nvatOutInvoiceDetail.getJshj());
        vmsMatch.setFpse(nvatOutInvoiceDetail.getHjse());
        vmsMatch.setLsje(lsjeTotal);
        vmsMatch.setLsse(lsseTotal);
        vmsMatch.setOidid(nvatOutInvoiceDetail.getOidid());
        vmsMatch.setDeptCode(tokenUser.getDeptCode());
        vmsMatch.setCreatBy(tokenUser.getUserCode());
        vmsMatch.setCreatTime(new Date());
        vmsMatch.setUpdateBy(tokenUser.getUserCode());
        vmsMatch.setUpdateTime(new Date());
        vmsMatchingService.save(vmsMatch);

        // 将发票明细转为主键为key，明细为value的map
        Map<Long, NvatOutInvoiceItems> nvatOutInvoiceItemListMap = nvatOutInvoiceItemList.stream()
                .collect(Collectors.toMap(NvatOutInvoiceItems::getIviid, item -> item, (value1, value2) -> value2));
        // 将流水信息转为主键为key，流水为value的map
        Map<Long, VmsTransacitonFlowInvoiceItemVo> rdidInfoListMap = rdidInfoList.stream()
                .collect(Collectors.toMap(VmsTransacitonFlowInvoiceItemVo::getId, item -> item, (value1, value2) -> value2));

        // 保存发票匹配流水详细记录
        List<VmsMatchingDetail> vmsMatchingDetailList = new ArrayList<>();
        for (NvatRevmapinvoitems nvatRevmapinvoitems : nvatRevmapinvoitemList) {
            VmsMatchingDetail vmsMatchingDetail = new VmsMatchingDetail();
            vmsMatchingDetail.setMatid(vmsMatch.getMatid());
            vmsMatchingDetail.setOidid(nvatRevmapinvoitems.getOidid());
            vmsMatchingDetail.setIviid(nvatRevmapinvoitems.getIviid());
            vmsMatchingDetail.setRdid(nvatRevmapinvoitems.getRdid());
            // 获取发票明细信息
            NvatOutInvoiceItems nvatOutInvoiceItem = nvatOutInvoiceItemListMap.get(nvatRevmapinvoitems.getIviid());
            if (nvatOutInvoiceItem == null) {
                throw new BusinessException(ResponseEnum.NOT_FIND_MATCH_ITEM_ERROR);
            }
            vmsMatchingDetail.setMxje(nvatOutInvoiceItem.getHsje());
            vmsMatchingDetail.setMxse(nvatOutInvoiceItem.getSe());
            vmsMatchingDetail.setMxsl(nvatOutInvoiceItem.getSl());
            // 获取流水信息
            VmsTransacitonFlowInvoiceItemVo rdidInfo = rdidInfoListMap.get(nvatRevmapinvoitems.getRdid());
            if (rdidInfo == null) {
                throw new BusinessException(ResponseEnum.NOT_FIND_MATCH_FLOW_ERROR);
            }
            vmsMatchingDetail.setLsje(rdidInfo.getBhsje().add(rdidInfo.getXxse()));
            vmsMatchingDetail.setLsse(rdidInfo.getXxse());
            vmsMatchingDetail.setLssl(rdidInfo.getSysl());

            vmsMatchingDetailList.add(vmsMatchingDetail);
        }
        vmsMatchingDetailService.saveBatch(vmsMatchingDetailList);

        return vmsMatch.getMatid();
    }

    @Override
    public Result<VmsMatchInvoiceInfoVo> getApplyDetail(Long applyId) {
        // 查询手工匹配流水信息
        LambdaQueryWrapper<VmsMatching> query = new LambdaQueryWrapper<>();
        query.eq(VmsMatching::getApplyId, applyId);
        VmsMatching vmsMatching = vmsMatchingService.getOne(query);
        if (vmsMatching == null) {
            return Result.ERROR(ResponseEnum.MATCH_FLOW_NOT_FIND_ERROR);
        }

        // 查询老系统发票信息
        LambdaQueryWrapper<NvatOutInvoiceDetails> invoiceQuery = new LambdaQueryWrapper<>();
        invoiceQuery.eq(NvatOutInvoiceDetails::getOidid, vmsMatching.getOidid());
        NvatOutInvoiceDetails nvatOutInvoiceDetail = nvatOutInvoiceDetailsMapper.selectOne(invoiceQuery);
        if (nvatOutInvoiceDetail == null) {
            return Result.ERROR(ResponseEnum.INVOICE_NOT_FOUND);
        }

        // 查询发票明细信息
        LambdaQueryWrapper<NvatOutInvoiceItems> itemQuery = new LambdaQueryWrapper<>();
        itemQuery.eq(NvatOutInvoiceItems::getOidid, nvatOutInvoiceDetail.getOidid());
        itemQuery.orderByAsc(NvatOutInvoiceItems::getIviid);
        List<NvatOutInvoiceItems> nvatOutInvoiceItemList = nvatOutInvoiceItemsMapper.selectList(itemQuery);

        // 实体类转换
        VmsMatchInvoiceDetailVo invoiceDetailVo = vmsMatchingService.convertToDetailVo(nvatOutInvoiceDetail, vmsMatching.getMatid());
        List<VmsMatchInvoiceItemVo> invoiceItemVoList = BeanUtils.copyListProperties(nvatOutInvoiceItemList, VmsMatchInvoiceItemVo::new);

        // 构造返回数据
        VmsMatchInvoiceInfoVo vmsMatchInvoiceInfoVo = new VmsMatchInvoiceInfoVo();
        vmsMatchInvoiceInfoVo.setInvoiceDetail(invoiceDetailVo);
        vmsMatchInvoiceInfoVo.setInvoiceItemList(invoiceItemVoList);

        return Result.OK(vmsMatchInvoiceInfoVo);
    }

    @Override
    public Result<Object> matchFlowRevokeProcess(Long applyId) {
        /**
         * 审批节点
         * 1、判断当前发票的匹配状态是否为已匹配、明细匹配的流水是否为已开票状态
         * 2、删除发票明细和匹配流水的关联关系
         * 3、将发票的匹配状态修改为未匹配、流水的开票状态修改为未开票、清空匹配时间
         */
        log.info("{}发票匹配流水撤销流程进行撤销，审批流id：{}", LOG_MSG, applyId);
        // 查询手工匹配流水信息
        LambdaQueryWrapper<VmsMatching> query1 = new LambdaQueryWrapper<>();
        query1.eq(VmsMatching::getApplyId, applyId);
        VmsMatching vmsMatching = vmsMatchingService.getOne(query1);
        if (vmsMatching == null) {
            return Result.ERROR(ResponseEnum.MATCH_FLOW_NOT_FIND_ERROR);
        }

        // 查询手工匹配流水详细信息
        LambdaQueryWrapper<VmsMatchingDetail> detailQuery = new LambdaQueryWrapper<>();
        detailQuery.eq(VmsMatchingDetail::getMatid, vmsMatching.getMatid());
        detailQuery.orderByAsc(VmsMatchingDetail::getMatdeid);
        List<VmsMatchingDetail> matchDetailList = vmsMatchingDetailService.list(detailQuery);
        if (CollectionUtil.isEmpty(matchDetailList)) {
            return Result.ERROR(ResponseEnum.ITEM_NOT_MATCH_FLOW_ERROR);
        }

        // 查询老系统发票信息
        LambdaQueryWrapper<NvatOutInvoiceDetails> invoiceQuery = new LambdaQueryWrapper<>();
        invoiceQuery.select(NvatOutInvoiceDetails::getOidid, NvatOutInvoiceDetails::getPpzt);
        invoiceQuery.eq(NvatOutInvoiceDetails::getOidid, vmsMatching.getOidid());
        NvatOutInvoiceDetails nvatOutInvoiceDetail = nvatOutInvoiceDetailsMapper.selectOne(invoiceQuery);
        if (nvatOutInvoiceDetail == null) {
            return Result.ERROR(ResponseEnum.INVOICE_NOT_FOUND);
        }
        // 校验发票的匹配状态是否为已匹配
        if (!CommonEnum.MATCHING_STATUS_1.getKey().equals(nvatOutInvoiceDetail.getPpzt())) {
            return Result.ERROR(ResponseEnum.MATCH_FLOW_REVOKE_PPZT_ERROR);
        }

        // 校验流水的开票状态是否为已开票
        for (VmsMatchingDetail vmsMatchingDetail : matchDetailList) {
            LambdaQueryWrapper<NvatTrandtadvaltaxsep> query = new LambdaQueryWrapper<>();
            query.select(NvatTrandtadvaltaxsep::getLszt);
            query.eq(NvatTrandtadvaltaxsep::getRdid, vmsMatchingDetail.getRdid());
            NvatTrandtadvaltaxsep nvatTrandtadvaltaxsep = vmsNvatTrandtadvaltaxsepMapper.selectOne(query);
            if (nvatTrandtadvaltaxsep == null || nvatTrandtadvaltaxsep.getLszt() != 3L) {
                return Result.ERROR(ResponseEnum.MATCH_FLOW_REVOKE_LSZT_ERROR);
            }
        }

        // 删除发票明细和流水关联关系
        LambdaQueryWrapper<NvatRevmapinvoitems> delete = new LambdaQueryWrapper<>();
        delete.eq(NvatRevmapinvoitems::getOidid, nvatOutInvoiceDetail.getOidid());
        nvatRevmapinvoitemsMapper.delete(delete);

        for (VmsMatchingDetail vmsMatchingDetail : matchDetailList) {
            // 获取流水的未开票金额
            LambdaQueryWrapper<NvatTrandtadvaltaxsep> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(NvatTrandtadvaltaxsep::getJyrmbje);
            queryWrapper.eq(NvatTrandtadvaltaxsep::getRdid, vmsMatchingDetail.getRdid());
            NvatTrandtadvaltaxsep one = vmsNvatTrandtadvaltaxsepMapper.selectOne(queryWrapper);
            BigDecimal wkpje = ObjectUtil.isEmpty(one.getJyrmbje()) ? BigDecimal.ZERO : one.getJyrmbje();
            // 将流水状态修改为未开票
            LambdaUpdateWrapper<NvatTrandtadvaltaxsep> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(NvatTrandtadvaltaxsep::getLszt, 1L);
            updateWrapper.set(NvatTrandtadvaltaxsep::getWkpje, wkpje);
            updateWrapper.eq(NvatTrandtadvaltaxsep::getRdid, vmsMatchingDetail.getRdid());
            vmsNvatTrandtadvaltaxsepMapper.update(null, updateWrapper);
        }

        // 将老系统发票的状态修改为未匹配、清空匹配时间
        LambdaUpdateWrapper<NvatOutInvoiceDetails> updateWrapper2 = new LambdaUpdateWrapper<>();
        updateWrapper2.set(NvatOutInvoiceDetails::getPpzt, CommonEnum.MATCHING_STATUS_0.getKey());
        updateWrapper2.set(NvatOutInvoiceDetails::getExpcol2, "");
        updateWrapper2.eq(NvatOutInvoiceDetails::getOidid, vmsMatching.getOidid());
        nvatOutInvoiceDetailsMapper.update(null, updateWrapper2);

        if (StringUtils.isNotBlank(vmsMatching.getFphm()) && vmsMatching.getFphm().length() == 20) {
            // 将数电发票的状态修改为未匹配
            LambdaUpdateWrapper<VmsFullOutInvoiceDetails> updateWrapper3 = new LambdaUpdateWrapper<>();
            updateWrapper3.set(VmsFullOutInvoiceDetails::getPpzt, CommonEnum.MATCHING_STATUS_0.getKey());
            updateWrapper3.set(VmsFullOutInvoiceDetails::getUpdateBy, SecurityUtils.getUserCode());
            updateWrapper3.set(VmsFullOutInvoiceDetails::getUpdateTime, new Date());
            updateWrapper3.eq(VmsFullOutInvoiceDetails::getFphm, vmsMatching.getFphm());
            vmsFullOutInvoiceDetailsService.update(updateWrapper3);
        }

        return Result.OK();
    }

}
